package com.whj.wkpt.service;

import com.whj.wkpt.entity.User;
import com.whj.wkpt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class
CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        // 根据用户角色添加权限
        switch (user.getRole()) {
            case "admin":
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                break;
            case "employer":
                authorities.add(new SimpleGrantedAuthority("ROLE_EMPLOYER"));
                break;
            case "freelancer":
                authorities.add(new SimpleGrantedAuthority("ROLE_FREELANCER"));
                break;
            default:
                throw new UsernameNotFoundException("Unsupported role: " + user.getRole());
        }

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .build();
    }
}